angular.module("starter.services",[])
	.service("MapManager",function(){
		
		//初始化地图
		this.map = new BMap.Map("map");
		var self= this;
		
		//显示地图
		this.showMap = function(){
			self.showUserLocation(function(point){
				self.map.centerAndZoom(point,1);
//				self.map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
				self.map.addControl(new BMap.ScaleControl());
			})
		};
		
		//显示用户位置
		this.showUserLocation = function(callback){
			
			
			self.getCurrentLocation().then(function(point){
				if(callback){
					callback(point);
				}
				var userMarker = new BMap.Marker(point);
				self.map.addOverlay(userMarker);
				self.map.panTo(point);
			}).catch(function(error){
				console.log(error);
			});
		}
		
		//定位，通过浏览器定位，定位到浏览器用户当前的位置
		this.getCurrentLocation = function(){
			
			return new Promise(function(success,fail){
				var geo = new BMap.Geolocation();
				//GeolocationResult -> point经纬度对象
				geo.getCurrentPosition(function(result){
					result.point? success(result.point):fail("定位失败");
				},{enableHighAccuracy: true});//允许使用GPS进行定位，可以提高定位精度
			});
		}
		
		//添加大头针
		this.addMarker = function(info,isShowInfo,isShowContent){
			
			//根据类型，地图上展示不同图标
			var iconUrl="img/ionic.png";
			switch (info.type){
				case 0:iconUrl="img/ionic.png";
					break;
				case 1:iconUrl="img/ionic.png";
					break;
				case 2:iconUrl="img/ionic.png";
					break;
				case 3:iconUrl="img/ionic.png";
					break;
				case 4:iconUrl="img/ionic.png";
					break;
				default:iconUrl="img/ionic.png";
					break;
			}
			
			var userMarker = new BMap.Marker(new BMap.Point(info.log,info.lat));
			userMarker.setIcon(new BMap.Icon(iconUrl,new BMap.Size(40,40)));
			var infoWindow = new BMap.InfoWindow(info.des);
			
			self.map.addOverlay(userMarker);
			
			//点击mark，触发事件
			if(isShowInfo){
				userMarker.addEventListener("click",function(){
					userMarker.openInfoWindow(infoWindow);
				});
			}
			
			//点击infowindow，就触发事件
			if (isShowContent) {
				
				
				infoWindow.addEventListener("open",isShowContent);
			}
			
		}
		
		//
		
		
	})
	
	
	
	
	.service("Show",function($ionicLoading,$timeout){
		this.showAlertDelay = function(message,delay){
			
			
			
			$ionicLoading.show({
		        template: message
	      });
	      $timeout(function () {
	        $ionicLoading.hide();
	      },delay*1000);
			
			
			
		};
	})

	.service("userInfo",function(){
		//保存数据到本地
		this.saveInfo = function(info){
			for(key in info){
				localStorage.setItem(key,info[key]);
			}
		}
		//
		this.getInfo = function(key){
			return localStorage.getItem(key);
		}
	})
	
	